package Region.socket;


import Region.DatabaseManager;
import Region.LogManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;

public class MasterSocketManager implements Runnable{
    private Socket socket;
    private BufferedReader input = null;
    private PrintWriter output = null;
    private boolean isRunning = false;

    private String MASTER;
    private DatabaseManager dataBaseManager;
    private LogManager logManager;
    private int regionPort;

    @Override
    public void run() {
        System.out.println("master监听线程启动成功");
        while (isRunning) {
            if (socket.isClosed() || socket.isInputShutdown() || socket.isOutputShutdown()) {
                isRunning = false;
                break;
            }
            try {
                //output.println("123");
                String Line = input.readLine();
                System.out.println(Line);

                int index_kuohao = Line.indexOf(']');
                String title = Line.substring(0,index_kuohao+1);
                String command = Line.substring(index_kuohao+1);
                handleCommand(title, command);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException | NullPointerException e) {
                e.printStackTrace();
            }
        }
    }

    public MasterSocketManager(String MASTER_IP, int port, int regionPort, DatabaseManager dataBaseManager, LogManager logManager) throws IOException {
        this.MASTER = MASTER_IP;
        this.socket = new Socket(MASTER, port);
        this.dataBaseManager = dataBaseManager;
        this.logManager = logManager;
        this.regionPort = regionPort;
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new PrintWriter(socket.getOutputStream(), true);
        isRunning = true;
    }

    public void handleCommand(String title, String command) throws IOException, SQLException {
        if(title.equals("<M2R>[4]")){
            //创建新表
            int index = command.indexOf(',');
            String tableName = command.substring(0, index);
            String sql = command.substring(index+1);

            logManager.createLog(tableName);
            logManager.addLog(tableName, sql);
            dataBaseManager.updateSQL(sql);

            sendToMaster("<R2M>[4]"+tableName);
        }else if (title.equals("<M2R>[5]")) {
            //恢复策略，从另一个Region处获得相应表的数据
            int index = command.indexOf(',');
            String tableName = command.substring(0, index);
            String ip_port = command.substring(index+1);

//            int index_port = command.indexOf(':');
//            String ip = ip_port.substring(0, index_port);
//            String port = ip_port.substring(index_port+1);

            logManager.deleteLog(tableName);
            logManager.createLog(tableName);
            Socket regionSocket = new Socket(ip_port,regionPort);
            RegionToRegionReceiveThread regionToRegionReceiveThread = new RegionToRegionReceiveThread(tableName, regionSocket, dataBaseManager, logManager);
            Thread receive = new Thread(regionToRegionReceiveThread);
            receive.start();

            sendToMaster("<R2M>[5]success");
        }else if(title.equals("<M2R>[11]")){
            //删除表
            int index = command.indexOf(',');
            String tableName = command.substring(0, index);
            String sql = command.substring(index+1);

            logManager.deleteLog(tableName);
//            logManager.addLog(tableName, sql);
            dataBaseManager.updateSQL(sql);

            sendToMaster("<R2M>[11]"+tableName);
        }
    }

    public void sendToMaster(String command){
        output.println(command);
        output.flush();
    }
}
